﻿using B.MESUI.Login.EquipmentManagement.DTO;
using B.MESUI.Login.LoginDtos;
using DevExpress.Xpo;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WorkflowCore2210A.Application.Dto;
using WorkflowCore2210A.Application.Dto.Input;
using WorkflowCore2210A.Application.Dto.Output;
using WorkflowCore2210A.Application.Enums;

namespace B.MESUI.Login.WorkflowCore.Definition
{
    public partial class StartDefinition : DevExpress.XtraEditors.XtraForm
    {
        private readonly List<FormField> FormFields;
        private WorkflowDefinitionOutput definition;
        private List<Control> dynamicControls = new List<Control>();

        public StartDefinition(List<FormField> formFields, WorkflowDefinitionOutput definition)
        {
            InitializeComponent();
            this.CenterToParent();
            this.FormFields = formFields;
            this.definition = definition;
            this.Resize += (s, e) => LayoutDynamicControls();
            LayoutDynamicControls();
        }

        private void LayoutDynamicControls()
        {
            // 先移除旧控件
            foreach (var ctrl in dynamicControls)
                this.Controls.Remove(ctrl);
            dynamicControls.Clear();

            int labelWidth = 100;
            int controlWidth = 300;
            int singleHeight = 36;
            int multiHeight = 100; // 富文本高度更大
            int margin = 15;       // 控件间隔更大

            // 计算所有控件组的总高度
            int totalHeight = 0;
            foreach (var field in FormFields)
            {
                totalHeight += (field.FieldType == FieldTypeEnum.RichText ? multiHeight : singleHeight) + margin;
            }
            if (FormFields.Count > 0) totalHeight -= margin;

            int startTop = (this.ClientSize.Height - totalHeight) / 2;
            if (startTop < 20) startTop = 20;

            int totalWidth = labelWidth + 16 + controlWidth;
            int startLeft = (this.ClientSize.Width - totalWidth) / 2;
            if (startLeft < 20) startLeft = 20;

            int curTop = startTop;

            for (int i = 0; i < FormFields.Count; i++)
            {
                var field = FormFields[i];
                int curHeight = (field.FieldType == FieldTypeEnum.RichText ) ? multiHeight : singleHeight;
                // int totalWidth = labelWidth + 16 + controlWidth; // This line is now redundant
                // int startLeft = (this.ClientSize.Width - totalWidth) / 2; // This line is now redundant

                // Label
                var label = new Label
                {
                    Text = field.DisplayFieldName,
                    Left = startLeft,
                    Top = curTop + (curHeight - singleHeight) / 2,
                    Width = labelWidth,
                    Height = singleHeight,
                    TextAlign = ContentAlignment.MiddleRight
                };
                this.Controls.Add(label);
                dynamicControls.Add(label);

                // 控件
                Control inputControl = null;
                switch (field.FieldType)
                {
                    case FieldTypeEnum.Text:
                        var textBox = new TextBox
                        {
                            Left = startLeft + labelWidth + 16,
                            Top = curTop,
                            Width = controlWidth,
                            Height = singleHeight
                        };
                        textBox.TextChanged += (s, e) => field.DisplayValue = textBox.Text;
                        inputControl = textBox;
                        break;
                    case FieldTypeEnum.RichText:
                        var richTextBox = new RichTextBox
                        {
                            Left = startLeft + labelWidth + 16,
                            Top = curTop,
                            Width = controlWidth,
                            Height = multiHeight
                        };
                        richTextBox.TextChanged += (s, e) => field.DisplayValue = richTextBox.Text;
                        inputControl = richTextBox;
                        break;
                    case FieldTypeEnum.Number:
                        var numBox = new DevExpress.XtraEditors.SpinEdit
                        {
                            Left = startLeft + labelWidth + 16,
                            Top = curTop,
                            Width = controlWidth,
                            Height = singleHeight
                        };
                        numBox.EditValueChanged += (s, e) => field.DisplayValue = numBox.Value.ToString();
                        inputControl = numBox;
                        break;
                    case FieldTypeEnum.Date:
                    case FieldTypeEnum.Time:
                        var dateEdit = new DevExpress.XtraEditors.DateEdit
                        {
                            Left = startLeft + labelWidth + 16,
                            Top = curTop,
                            Width = controlWidth,
                            Height = singleHeight
                        };
                        dateEdit.EditValue = null; // 让初始值为空
                        dateEdit.Properties.NullText = "请选择"; // 显示“请选择”
                        dateEdit.EditValueChanged += (s, e) => field.DisplayValue = dateEdit.Text;
                        inputControl = dateEdit;
                        break;
                    default:
                        var defaultBox = new TextBox
                        {
                            Left = startLeft + labelWidth + 16,
                            Top = curTop,
                            Width = controlWidth,
                            Height = singleHeight
                        };
                        defaultBox.TextChanged += (s, e) => field.DisplayValue = defaultBox.Text;
                        inputControl = defaultBox;
                        break;
                }

                if (inputControl != null)
                {
                    this.Controls.Add(inputControl);
                    dynamicControls.Add(inputControl);
                }

                curTop += curHeight + margin;
            }

            // 添加保存按钮
            var saveButton = new Button
            {
                Text = "发起审批",
                Width = 100,
                Height = 36,
                Left = (this.ClientSize.Width - 100) / 2,
                Top = curTop + 20
            };
            saveButton.Click += async(s, e) =>
            {
                // 校验必填项
                foreach (var field in FormFields)
                {
                    if ((field.FieldType == FieldTypeEnum.Date || field.FieldType == FieldTypeEnum.Time) && string.IsNullOrWhiteSpace(field.DisplayValue))
                    {
                        MessageBox.Show($"{field.DisplayFieldName}不能为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                }
                var data = new WorkflowStartInput();
                data.Title=definition.Title;
                data.Version= definition.Version;
                data.WorkflowDefinitionId=definition.DefinitionId;
                data.FormData=JsonConvert.SerializeObject(FormFields);
                data.UserId=AppSession.UserId;
                data.UserName=AppSession.Username;
                // 序列化为 JSON
                string json = JsonConvert.SerializeObject(data);
                // 发送 POST 请求
                string apiUrl = $"{BaseUrl.WorkflowUrl}Workflow/StartWorkflow"; // 替换为你的接口地址
                using (var client = new HttpClient())
                {
                    var content = new StringContent(json, Encoding.UTF8, "application/json");
                    try
                    {
                        var response = await client.PostAsync(apiUrl, content);
                        if (response.IsSuccessStatusCode)
                        {
                            MessageBox.Show("发起审批成功！");
                        }
                        else
                        {
                            string resp = await response.Content.ReadAsStringAsync();
                            MessageBox.Show("保存失败：" + resp);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("请求异常：" + ex.Message);
                    }
                }
                this.DialogResult = DialogResult.OK; // 关闭窗口并返回OK
                this.Close();
            };
            this.Controls.Add(saveButton);
            dynamicControls.Add(saveButton);
        }
        
    }
}